package org.leumasjaffe.initiativeTracker.distributed.controller;

import static org.leumasjaffe.initiativeTracker.operator.InitiativeController.tracker;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.leumasjaffe.initiativeTracker.operator.CharacterLinker;
import org.leumasjaffe.initiativeTracker.operator.InitiativeController;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

import edu.wpi.heineman.xml.Message;
import edu.wpi.heineman.client.IMessageHandler;

@NonNullByDefault
public class ChangeTurnHandler implements IMessageHandler {

	@Override
	public void process(Message response) {
		NamedNodeMap map = response.contents.getFirstChild().getAttributes();
		Node dotNode = map.getNamedItem("dot");	
		
		@SuppressWarnings("null")
		InitiativeController tracker = tracker(map.getNamedItem("game").getNodeValue());
		
		int nextTurn = (tracker.root.getSubTurn()+1)%tracker.list.size();
		CharacterLinker cl = tracker.list.get(nextTurn);
		
		if (dotNode != null) {
			int dot = Integer.decode(dotNode.getNodeValue());
			cl.getCharacter().setDot(dot);
		}
		
		tracker.root.nextTurn();	
	}
	
	@Override
	public IMessageHandler newCopy() {
		return new ChangeTurnHandler();
	}

}
